package com.coldworks.coldjoke.adapter;

import java.util.List;

import com.coldworks.base.manager.BaseStorageManager;
import com.coldworks.coldjoke.R;
import com.coldworks.coldjoke.model.TopicModel;
import com.coldworks.coldjoke.task.AsyncImgLoader;
import com.coldworks.coldjoke.task.AsyncImgLoader.UrlImageCallback;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TopicListViewAdapter extends BaseAdapter {

	private List<TopicModel> topicInfos;
	private Context context;

	public TopicListViewAdapter(Context context, List<TopicModel> topicInfos) {
		this.topicInfos = topicInfos;
		this.context = context;
	}

	@Override
	public int getCount() {
		return topicInfos.size();
	}

	@Override
	public Object getItem(int position) {
		return topicInfos.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		TopicViewHolder holder;
		if (convertView == null) {
			convertView = LayoutInflater.from(this.context).inflate(
					R.layout.navigation_topic_listview_item, null);
			holder = new TopicViewHolder();
			holder.topicTitleView = (TextView) convertView
					.findViewById(R.id.topic_title);
			holder.topicSummaryView = (TextView) convertView
					.findViewById(R.id.topic_summary);
			holder.imageView = (ImageView) convertView
					.findViewById(R.id.topic_image);
			convertView.setTag(holder);
		} else {
			holder = (TopicViewHolder) convertView.getTag();
		}

		TopicModel topicInfo = topicInfos.get(position);

		holder.topicTitleView.setText(topicInfo.getTitle());
		holder.topicSummaryView.setText(topicInfo.getSummary());

		String imgUrl = topicInfo.getImgUrl();

		if (!topicInfo.getImgUrl().equals("")) {
			holder.imageView.setBackgroundResource(R.drawable.ic_photo);
			Bitmap cachedImage = AsyncImgLoader.getInstance()
					.loadDrawableByUrl(
							context,
							imgUrl,
							holder.imageView,
							new UrlImageCallback() {
								@Override
								public void imageLoaded(Bitmap imageDrawable,
										ImageView imageView, String imageUrl) {
									imageView.setImageBitmap(imageDrawable);
								}
							}, BaseStorageManager.getInstance().getImgDir(),
							false);
			if (cachedImage != null) {
				holder.imageView.setImageBitmap(cachedImage);
			} else {
				holder.imageView.setBackgroundResource(R.drawable.ic_photo);
			}
		}
		return convertView;
	}

	static class TopicViewHolder {
		ImageView imageView;
		TextView topicTitleView;
		TextView topicSummaryView;
	}

}
